package com.example.demo.service;

import com.example.demo.model.Product;
import jakarta.annotation.Resource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CollectionService {

    @Resource
    private MongoTemplate mongoTemplate;

    public Object createCollection() {
        var collectionName = "tasks";
        mongoTemplate.createCollection(collectionName);
        return mongoTemplate.collectionExists(collectionName) ? "Collection created successfully" : "Failed to create collection";
    }

    public List<Product> findProductByName(String name) {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").regex( name, "i")); /// "i" for case-insensitive
        return mongoTemplate.find(query, Product.class);
    }

    public List<Product> findProductByPrice(Double price) {
        Query query = new Query();
        query.addCriteria(Criteria.where("price").is(price)); // greater than or equal to
        return mongoTemplate.find(query, Product.class);
    }

    public List<Product> findProductByPriceBetween(Double startPrice, double endPrice) {
        Query query = new Query();
        query.addCriteria(Criteria.where("price").gte(startPrice).lte(endPrice));
        return mongoTemplate.find(query, Product.class);
    }

}
